import React from 'react'
import routes from "@/router"
import { useRoutes } from "react-router-dom"
import deepClone from '../utils/deppClone';

export default function DynamicRouter() {
    //筛选出来你能访问的路由，再去加载
    const userInfo = JSON.parse(localStorage.userInfo || "{}")
    //判断userInfo是不是空对象
    let news = deepClone(routes)
    if (Object.keys(userInfo) != 0) {
        //menus = ["/home/user","/home/role"]
        //对比:[ { path: "main", element: <Main /> },]
        const {menus} = userInfo.role
        const userRoutes = menus.map(item=>{
            return item.substr(6)
        })
        const index = routes.findIndex(item=>item.path=="/home")
        //克隆
        let tempArray = [...routes[index].children]
        tempArray = tempArray.filter(item=>{
            if(userRoutes.includes(item.path)){
                return true
            }
        })
        //我们是直接覆盖routes的值
        news[index].children = tempArray
    }
    const elements = useRoutes(news)
    return elements
}
